<template>
  <div class="app-container">
    <div class="hor mg-b-10">
      <el-input
        style="width: 200px"
        class="mg-l-10"
        placeholder="请输入权限名"
        v-model="searchName"
        @clear="onInputClear(1)"
        clearable>
      </el-input>
      <el-button type="primary" icon="el-icon-search" @click="onClickSearch()" class="mg-l-20">搜索
      </el-button>
      <div class="flex1"></div>
      <el-button type="primary" icon="el-icon-plus" class="mg-l-10"
                 @click="onClickAdd()"></el-button>
      <el-button-group class="mg-l-10">
        <el-tooltip class="item" effect="dark" content="删除后无法恢复" placement="bottom">
          <el-button type="danger"
                     @click="isHadPermission([''])?onDeleteDialogShow = true:noPermissionHint()">
            删除
          </el-button>
        </el-tooltip>

      </el-button-group>
    </div>
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="allList"
      :height="autoHeight"
      element-loading-text="Loading"
      @cell-click="onCellClick"
      @selection-change="handleSelectionChange"
      @row-click="onItemClick"
      @row-dblclick="onItemDoubleClick"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column align="center" label="ID" width="150">
        <template slot-scope="scope">
          {{ scope.row.id}}
        </template>
      </el-table-column>
      <el-table-column label="权限描述">
        <template slot-scope="scope">
          {{ scope.row.description }}
        </template>
      </el-table-column>
      <el-table-column label="权限名(判断键)" width="200">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="所属角色数" width="150" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.authRoles.length }}</span>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="操作" width="150" align="center">
        <template slot-scope="scope">
          <div class="ver hor-center">
            <el-button type="warning"   size="small"
                       @click.stop="onClickView(scope.row)">查看
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="hor">
      <div class="flex1"></div>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[20, 50, 100, 200]"
        :page-size="size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="mg-t-10">
      </el-pagination>
    </div>
    <el-dialog
      title="编辑用户信息"
      :visible.sync="infoDialogShow"
      width="400px"
      @open="onDialogOpen"
      center>
      <div class="ver match-width">
        <el-form label-width="130px">
          <el-form-item label="权限描述">
            <el-input v-model="detail.description" maxlength="500" show-word-limit
                      type="textarea"
                      :autosize="{ minRows: 4, maxRows: 8}"/>
          </el-form-item>
          <el-form-item label="权限名(判断键)">
            <el-input v-model="detail.name"/>
          </el-form-item>
        </el-form>

        <div class="hor match-width ver-center hor-center" v-if="isHadPermission([''])">
          <el-button @click="infoDialogShow = false">取 消</el-button>
          <el-button type="primary" @click="onClickSave" :loading="onSaveLoading">确 定</el-button>
        </div>

      </div>
    </el-dialog>
    <el-dialog
      title="提示"
      :visible.sync="onDeleteDialogShow"
      width="30%">
      <span>删除后无法恢复</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="onDeleteDialogShow = false">取消</el-button>
    <el-button type="danger" @click="batchDelete()" :loading="onDeleteLoading">删除</el-button>
  </span>
    </el-dialog>

  </div>

</template>
<style>
</style>
<script>
import { deleteAccess, queryAccessList, saveAccess } from '@/api/auth/auth'

export default {
  filters: {
    // statusFilter(status) {
    //   const statusMap = {
    //     published: 'success',
    //     draft: 'gray',
    //     deleted: 'danger'
    //   }
    //   return statusMap[status]
    // }
  },
  data() {
    return {
      allList: null,
      allAccess: null,
      page: 1,
      size: 20,
      total: 0,
      autoHeight: 800,//根据屏幕高度自动计算的高度
      //筛选参数
      params: {},
      searchName: '',
      selectRowList: [],
      onDeleteDialogShow: false,
      onDeleteLoading: false,

      //信息窗口
      infoDialogShow: false,
      detail: {},
      selectAccess: [],
      onSaveLoading: false,

      listLoading: true
    }
  }, beforeMount() {
    this.authHeight = document.body.scrollHeight - 190
  }, mounted() {
    this.fetchData()
  },
  created() {

  },
  methods: {
    fetchData() {
      this.listLoading = true
      const data = new FormData()
      for (var key in this.params) {//直接去除掉空值的对象
        if (this.isEmpty(this.params[key])) {
          delete this.params[key]
        }
      }
      console.log(this.params)
      data.append('params', JSON.stringify(this.params))
      data.append('page', this.page)
      data.append('size', this.size)
      data.append('sortJsonStr', null)

      queryAccessList(data).then(response => {
        this.allList = response.data
        this.total = response.totalElements

        this.listLoading = false
      })
    }, batchDelete() {
      const _this = this
      if (this.selectRowList == null || this.selectRowList.length == 0) {
        this.$message({
          message: '请选择对象',
          type: 'warning',
          duration: 1000
        })
        return
      }
      const array = []
      for (let i = 0; i < this.selectRowList.length; i++) {
        array.push(this.selectRowList[i].id)
      }
      const data = new FormData()
      data.append('ids', array)

      this.$message({
        message: '操作中',
        type: 'warning',
        duration: 1000
      })
      this.onDeleteLoading = true
      deleteAccess(data).then(response => {
        this.$message({
          message: '删除成功',
          type: 'success',
          duration: 3000
        })
        this.onDeleteLoading = false
        this.onDeleteDialogShow = false
        _this.fetchData()
      }).catch((e) => {
        this.onDeleteLoading = false
      })
    }, getRoleList() {
      const data = new FormData()
      queryAccessList(data).then(response => {
        this.allAccess = response.data
      })
    }, saveOrganization() {

      this.onSaveLoading = true
      //把选择的权限赋值过去
      if (this.selectAccess != null) {
        this.detail.authAccesses = []
        for (let i = 0; i < this.selectAccess.length; i++) {
          for (let j = 0; j < this.allAccess.length; j++) {
            if (this.selectAccess[i] === this.allAccess[j].id) {
              this.detail.authAccesses.push(this.allAccess[j])
            }
          }
        }
      }
      const data = new FormData()
      data.append('json', JSON.stringify(this.detail))
      saveAccess(data).then(response => {
        this.onSaveLoading = false
        this.infoDialogShow = false
        this.$message({
          message: '保存成功',
          type: 'success',
          duration: 2000
        })
        this.fetchData()
      }).catch((e) => {
        this.onSaveLoading = false
      })
    }
    , handleSizeChange(val) {
      this.size = val
      this.fetchData()
    }, handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    }, onClickSearch() {//点击搜索
      if (!this.isEmpty(this.searchName)) {
        this.params['name_like'] = ('%' + this.searchName.trim() + '%')
      } else {
        this.params['name_like'] = ''
      }

      this.fetchData()
    }, onInputClear(type) {//1.姓名
      if (type === 1) {
        this.searchName = ''
      } else if (type === 2) {
        this.searchPhone = ''
      }
      this.onClickSearch()

    }, handleSelectionChange(rowList) {//多选变化监听
      this.selectRowList = rowList
    }, onCellClick(row, column, cell, event) {
      if (column.type == 'selection') {
        this.$refs.table.toggleRowSelection(row)
      }
    }
    , onItemClick(row) {//单行点击
    }
    , onItemDoubleClick(row) {//单行双击
      this.infoDialogShow = true
      this.detail = row
      // console.log(this.detail)
    }
    , onClickAdd() {
      if (!this.isHadPermission([''])) {
        this.noPermissionHint()
        return
      }

      this.detail = {}
      this.infoDialogShow = true
    }, onDialogOpen() {
      this.getRoleList()
      //拼装权限列表选择
      this.selectAccess.splice(0, this.selectAccess.length)
      if (this.detail.authAccesses != null) {
        for (let i = 0; i < this.detail.authAccesses.length; i++) {
          this.selectAccess.push(this.detail.authAccesses[i].id)
        }
      }
    }, onAccessChange(val) {
      this.selectAccess = val
      console.log(this.selectAccess)
    }, onClickSave() {//点击保存
      this.saveOrganization()
    }, onClickView(row) {
      this.infoDialogShow = true
      this.detail = row
    }
  }
}
</script>
